import 'package:mediapipe_task_vision_example/footstep/footstep.dart';

class FootStep2 implements FootStep {
  double UPDATE_FOOT_DIS = 0.01;
  double CHANGE_STEP_DIS = 0.1;

  // double STEP_RECT_RATIO  0.2;
  FootStepListener? _stepListener;
  var _prePosition = Position(0, 0);
  StepType _preStepType = StepType.unknown;
  StepAdapter? _stepAdapter;

  @override
  void setStepListener(FootStepListener stepListener) {
    _stepListener = stepListener;
  }

  @override
  void update(Position footPosition) {
    _footStep(footPosition);
  }

  void _footStep(Position footPos) {
    if (_stepAdapter == null) {
      return;
    }
    if (footPos.x > 1 || footPos.y > 1) {
      return;
    }
    var move = Position(footPos.x - _prePosition.x, footPos.y - _prePosition.y);
    if (move.x.abs() >= CHANGE_STEP_DIS * _stepAdapter!.scale ||
        move.y.abs() >= UPDATE_FOOT_DIS * _stepAdapter!.scale) {
      double _stepDistance = 1;
      StepType stepType = StepType.unknown;
      for (int i = 0; i < _stepAdapter!.steps.length; i++) {
        var stepPosition = _stepAdapter!.steps[i];
        var stepDistanceX = stepPosition.x - footPos.x;
        var stepDistanceY = stepPosition.y - footPos.y;
        var stepDistance = stepDistanceX.abs() + stepDistanceY.abs();
        if (stepDistance < _stepDistance) {
          // if (stepDistanceX.abs() < _stepAdapter!.rect_wh/2 && stepDistanceY.abs() < _stepAdapter!.rect_wh/2 ) {
            _stepDistance = stepDistance;
            stepType = stepPosition.stepType;
          // }
        }
      }
      if (stepType != _preStepType) {
        _stepListener!.step(_preStepType, KeyType.keyup, footPos);
        _stepListener!.step(stepType, KeyType.keydown, footPos);
      }else{
        //相同脚步，连击判断
        // if (move.y < 0 && move.x.abs() < _stepAdapter!.rect_wh) {
          if (move.y < 0) {
          _stepListener!.step(_preStepType, KeyType.keyup, footPos);
        } else {
          _stepListener!.step(stepType, KeyType.keydown, footPos);
        }
      }
      _preStepType = stepType;
      _prePosition = footPos;
    }
  }

  @override
  void setStepAdapter(stepAdapter) {
    _stepAdapter = stepAdapter;
  }
}
